<?php

namespace app\services;

use app\payment\PayFactory;
use app\traits\Page;
use plugin\admin\app\model\Reward;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\UserPropertyLog;
use plugin\admin\app\model\Video;

class RewardService
{
    public static function add($videoId, $money)
    {
        if ($money < 10) {
            throw new \Exception('打赏金额不能小于10');
        }

        $video = Video::where('id', $videoId)->first();

        if (!$video) {
            throw new \Exception('不存在的视频');
        }

        if ($video['user_id'] == get_user_id()) {
            throw new \Exception('不能打赏自己');
        }

        PropertyService::reduce(get_user_id(), PayFactory::SB, $money, UserPropertyLog::REWARD_OUTCOME);
        PropertyService::add($video['user_id'], PayFactory::SB, $money, UserPropertyLog::REWARD_INCOME);

        Reward::insertGetId([
            'user_id' => get_user_id(),
            'video_user_id' => $video['user_id'],
            'video_id' => $videoId,
            'amount' => $money,
            'created_time' => date('Y-m-d H:i:s')
        ]);
    }

    public static function list($page, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $query = Reward::where('video_user_id', get_user_id());

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('id')->get()->toArray();

        $rewardUserIds = array_column($list, 'user_id');
        $users =  UserProfile::select(['user_id', 'nickname', 'avatar', 'no'])->whereIn('user_id', $rewardUserIds)->get()->toArray();
        $users = array_combine(
            array_column($users, 'user_id'),
            array_values($users)
        );

        $videoIds = array_column($list, 'video_id');
        $videos = Video::select(['id', 'thumb', 'desc'])->whereIn('id', $videoIds)->get()->toArray();
        $videos = array_combine(
            array_column($videos, 'id'),
            array_values($videos)
        );

        foreach ($list as $key=>$item) {
            $item['user_info'] = $users[$item['user_id']];
            $video = $videos[$item['video_id']];
            $video['thumb'] = full_url($video['thumb']);
            $item['video_info'] = $video;
            $item['format_time'] = diff_time($item['created_time']);
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }
}